package co.fitstart.admin.web.controller.user.distributor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.BusinessException;
import com.demo2do.core.support.Page;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.core.web.utils.WebUtils;

import co.fitstart.admin.entity.search.DistributorSearch;
import co.fitstart.admin.service.DistributorService;
import co.fitstart.admin.service.UserService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.entity.user.User;
import co.fitstart.entity.user.distributor.Distributor;

@Controller
@RequestMapping("/distributors")
@MenuSetting("menu-user")
public class DistributorController {
    
    private static final Logger logger = LoggerFactory.getLogger(DistributorController.class);
    
    @Autowired
    private DistributorService distributorService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-distributor")
    public ModelAndView list(Page page, HttpServletRequest request) {
        
        ModelAndView modelAndView = new ModelAndView("user/distributor/distributor-list");
        
        List<Distributor> distributors = distributorService.list(page);
        modelAndView.addObject("distributors", distributors);
        
        modelAndView.addObject("page", page);
        
        modelAndView.addObject("refer", "list");
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
        
        return modelAndView;
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public ModelAndView search() {
        ModelAndView modelAndView = new ModelAndView("user/distributor/distributor-search");
        return modelAndView;
    }
    
    /**
     * 
     * @param search
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
    @MenuSetting("submenu-distributor")
    public ModelAndView onSearch(DistributorSearch search, Page page, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("user/distributor/distributor-list");
        
        List<Distributor> distributors = distributorService.search(search, page);
        modelAndView.addObject("distributors", distributors);
        
        modelAndView.addObject("page", page);
        
        modelAndView.addObject("refer", "list");
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
        
        return modelAndView;
    }
    
    /**
     * 
     * @param distributorId
     * @return
     */
    @RequestMapping(value = "/{distributorId}", method = RequestMethod.GET)
    @MenuSetting("submenu-distributor")
    public ModelAndView view(@PathVariable("distributorId") Long distributorId) {
        
        ModelAndView modelAndView = new ModelAndView("user/distributor/distributor-view");
        
        Distributor distributor = distributorService.load(distributorId);
        modelAndView.addObject("distributor", distributor);
        
        return modelAndView;
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public ModelAndView create() {
        ModelAndView modelAndView = new ModelAndView("user/distributor/distributor-create");
        return modelAndView;
    }
    
    /**
     * 
     * @param mobile
     * @return
     */
    @RequestMapping(value = "/search-user", method = RequestMethod.GET, params = "filters")
    public @ResponseBody String onSearchUser(@RequestParam("mobile") String mobile) {
        Result result = new Result();
        
        try {
            
            User user = userService.load(mobile);
            String name = StringUtils.isEmpty(user.getName()) ? user.getMobile() : user.getName();
            result.success().data("username", name)
                            .data("userId", user.getId())
                            .message("查询用户成功");
            
        } catch (BusinessException e) {
            
            result.fail().message(e.getMessage());
            
        } catch (Exception e) {
            
            logger.error("onSearchUser() - ", e);
            result.fail().message("查询用户失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    public @ResponseBody String onCreate(@RequestParam("userId") Long userId,
                                         @RequestParam(value = "account", required = false) String account,
                                         @RequestParam(value = "kickback", required = false) int kickback,
                                         @RequestParam(value = "realName", required = false) String realName,
                                         @RequestParam(value = "webchatId", required = false) String webchatId) {
        Result result = new Result();
        
        try {
            
            User user = userService.load(userId);
            Distributor distributor = new Distributor(user, kickback, realName, account, webchatId);
            
            distributorService.createDistributor(distributor);
            
            result.success().message("明星代言人创建成功");
            
        } catch (BusinessException e) {
            
            result.fail().message(e.getMessage());
            
        } catch (Exception e) {
            
            logger.error("onCreate() - ", e);
            result.fail().message("创建代言人失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param distributorId
     * @return
     */
    @RequestMapping(value = "/{distributorId}/delete", method = RequestMethod.GET)
    public ModelAndView delete(@PathVariable("distributorId") Long distributorId) {
        ModelAndView modelAndView = new ModelAndView("user/distributor/distributor-delete");
        
        modelAndView.addObject("distributorId", distributorId);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param distributor
     * @return
     */
    @RequestMapping(value = "/{distributorId}", method = RequestMethod.DELETE)
    public @ResponseBody String onDelete(@Preloading("id") Distributor distributor) {
        Result result = new Result();
        
        try {
            
            distributorService.deleteDistributor(distributor);
            
            result.success().message("删除代言人成功");
            
        } catch (Exception e) {
            
            logger.error("onDelete() - ", e);
            result.fail().message("删除代言人失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
}
